/*
 * File Name: client.c
 *
 * Group Members: Cassie Chin (cassiechin9793@gmail.com)
 *                Stephen Smetana (stephensmetana11@gmail.com)
 *                Logan Widick (logan.widick@gmail.com)
 *
 * File Description:
 *
 *
 * Sources: http://beej.us/guide/bgnet/examples/client.c
 *          This code is originally intended to connect to the host you specify
 *          on the command line. For example "./client 129.120.151.94" will 
 *          connect to 129.120.151.94
 *
 *          We took the outline of this code and incorporated the ability to
 *          send messages to the specified server.
 */

#include "httpstuff.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define PORT "60000" // the port client will be connecting to 

#define MAXDATASIZE 10000 // max number of bytes we can get at once
#define BUFFERSIZE 256

int main(int argc, char *argv[]) {
  char send_message[BUFFERSIZE];
  char buf[MAXDATASIZE];

  int rv;
  char s[INET6_ADDRSTRLEN];

  if (argc != 2) {
    fprintf(stderr,"usage: client hostname\n");
    exit(1);
  }

  FilePointerSet mySet;
  if(openClientConnection(PORT, argv[1], &mySet) != 0){
	  fprintf(stderr, "error connecting\n");
	  exit(1);
  }

  /* Use fgets and then write the message to the socket */
  while (1) {
    fgets (send_message, BUFFERSIZE, stdin);
    int writeval = fwrite (send_message, sizeof(char), strlen(send_message), mySet.outFile);
    if (strncmp(send_message, "exit", 4) == 0 || writeval <= 0)
      break;
  }

  int numbytes = 0;
  if ((numbytes = fread(buf, sizeof(char), MAXDATASIZE-1, mySet.inFile)) <= 0) {
    perror("recv");
    exit(1);
  }

  buf[numbytes] = '\0';

  printf("client: received '%s'\n",buf);

  fclose(mySet.inFile);
  fclose(mySet.outFile);

  return 0;
}
